#!/usr/bin/python

import direct.directbase.DirectStart
from pandac.PandaModules import *
from direct.task import Task
    
import procmodels

from LogWriter import log
from AudioMgr import audio
from Explosion import *

class Weapon(object):
    '''
    pew pew
    
    FIXME : weapon code seems to be memory-leaky; might actually be explosion
    code though
    '''
    def __init__(_, worldmgr, originNP, model, cooldown, drain, speed, offset=Point3(0,0,0)):
        _.worldmgr = worldmgr
        _.originNP = originNP
        _.originName = _.originNP.getName()
        _.model = model
        _.offset = offset
        
        _.cooldown = 0.0
        _.prevtime = 0.0
        _.max_cooldown = cooldown
        _.speed = speed
        
        _.life = 0.0
        _.max_life = 1.8
        _.drain = drain

        _.bullets = []

        taskMgr.add(_.bulletTask, _.originNP.getName()+'_pewpew')

    def pewpew(_):
        if _.cooldown <= 0:
            bullet = procmodels.loadModel(_.model)
            bullet.setPos(_.originNP, _.offset)
            bullet.setHpr(_.originNP.getHpr())
            bullet.reparentTo(render)

            _.worldmgr.addPandaBody(bullet, '_bullet',
                CollisionSphere(0,0,0, 0.25))
                #CollisionSegment(0,-0.5,0, 0,0.5,0))#, collideInto=False)
##            cNP = bullet.attachNewNode(CollisionNode('_bullet'))
##            cNP.node().addSolid(CollisionSegment(0,-0.5,0, 0,0.5,0))
##            if DEBUG is True:
##                cNP.show()

            _.bullets.append([bullet, _.max_life])
            _.cooldown = _.max_cooldown
            return bullet
        else:
            return None

    def bulletTask(_, task): 
        t = task.time - _.prevtime
        
        for b in _.bullets:
            if b[1] <= 0:
                _.destroyBullet(b)
            else:
                b[0].setFluidPos(b[0], 0,_.speed * t,0)
                b[1] -= t


        if _.cooldown > 0:
            _.cooldown -= t

        _.prevtime = task.time

        return Task.cont 

    def destroyBullet(_, b):
        playExplosion(b[0].getPos(), 1.5, damage=_.worldmgr)
        b[0].removeNode()
        _.bullets.pop(_.bullets.index(b))
        del b
